package com.killer.texreader.Activity;

import android.content.Intent;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.widget.TextView;

import com.killer.texreader.R;
import com.killer.texreader.util.Globals;
import com.killer.texreader.util.PageDao;
import com.killer.texreader.util.TxtDao;
import com.killer.texreader.view.MyView;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;

public class MainActivity extends AppCompatActivity {
    private Map<String, Object> txtMap;
    private StringBuffer sb = new StringBuffer();
    private int pagenum = 1;
    private int lineCount;
    private Map<String, Object> pageMap = new HashMap<>();
    private String fullPath;
    private Handler handler;
    private MyView contentView;
    private TextView pageTxt;
    private int nowPager = 1;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Globals.init(this);
        setContentView(R.layout.activity_main);

       // Log.i("killer","Environment.getExternalStorageDirectory().getAbsolutePath()"+Environment.getExternalStorageDirectory().getAbsolutePath());

        contentView = (MyView) findViewById(R.id.content_view);
        pageTxt = (TextView) findViewById(R.id.page_txt);

        handler=new Handler(){
            @Override
            public void handleMessage(Message msg) {
                if (msg.what ==0){
                    //提示分了多少页
                    Log.i("killer","已分页"+(pagenum-1));
                   // pageTxt.setText("已分页"+(pagenum-1));
                }else if (msg.what==1){
                    //已完成分页
                    pageTxt.setText("页码"+nowPager+"/"+pagenum);
                }

            }
        };

        Log.i("killer","路径        "+Globals.fullPath);
        Log.i("killer","路径 11       "+Environment.getExternalStorageDirectory().getAbsolutePath()+"/zengguofanletter.txt");
        fullPath = Globals.fullPath;
        //  = Environment.getExternalStorageDirectory().getAbsolutePath()+"/zengguofanletter.txt";
        //将文本信息插入到txt表中
        TxtDao.insertTxtData(fullPath);

        txtMap = TxtDao.findTxtDataByFullPath(fullPath);
        //判断是否已分页
        if ((int)txtMap.get("overFlag")==0){
            Thread  t = new Thread(){
                @Override
                public void run() {
                    //分页
                    try {
                        //BufferedReader br  = new BufferedReader(new InputStreamReader(new FileInputStream(fullPath),"GBK"));
                        BufferedReader br  = new BufferedReader(new InputStreamReader(new FileInputStream(fullPath)));
                        String line = null;
                        while ((line = br.readLine())!=null){
                            while (line.length()>Globals.LINE_CHAR_COUNT){
                                String str = line.substring(0,Globals.LINE_CHAR_COUNT);
                                line = line.substring(Globals.LINE_CHAR_COUNT);
                                addLine(str);
                            }
                            addLine(line);
                        }
                        //完成分页
                        handler.sendEmptyMessage(1);
                        br.close();
                        TxtDao.updateTxtOverFlag(fullPath);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            };
            t.start();
        }else {
            pagenum = PageDao.findAllCount((Integer) txtMap.get("txtid"));

            //跳到之前阅读的页数
            nowPager = (int) txtMap.get("now_pager");
            contentView.changeData();
        }
    }



    private void addLine(String str) throws InterruptedException {
        sb.append(str);
        sb.append(Globals.END_FLAG);
        lineCount++;
        if (lineCount==Globals.LINE_COUNT){
            pageMap.put("txtid",txtMap.get("txtid"));
            pageMap.put("pagenum",pagenum++);
            pageMap.put("content",sb.toString());
            PageDao.insertPageData(pageMap);
            Thread.sleep(5);
            handler.sendEmptyMessage(0);
            if (pagenum==10){
                contentView.changeData();
            }
            lineCount = 0;
            sb = new StringBuffer();
        }
    }




    public Map<String, Object> getTxtMap() {
        return txtMap;
    }

    public void setTxtMap(Map<String, Object> txtMap) {
        this.txtMap = txtMap;
    }

    public Handler getHandler() {
        return handler;
    }

    public void setHandler(Handler handler) {
        this.handler = handler;
    }

    public int getNowPager() {
        return nowPager;
    }

    public void setNowPager(int nowPager) {
        this.nowPager = nowPager;
    }

    public int getPagenum() {
        return pagenum;
    }

    public void setPagenum(int pagenum) {
        this.pagenum = pagenum;
    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode==KeyEvent.KEYCODE_MENU){
            finish();
            Intent intent = new Intent(this,selectFileActivity.class);
           // startActivityForResult(intent,1);
            startActivity(intent);
            return false;
        }
        return super.onKeyDown(keyCode, event);
    }

   /* @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode==1 && resultCode==1){
            String msg=data.getStringExtra("msg");
            fullPath = msg;
        }
    }*/

    @Override
    protected void onDestroy() {
        TxtDao.updateNowPage(nowPager,fullPath);

        super.onDestroy();
    }
}
